#include "packet.hpp"
#include <string.h>
#include <assert.h>

Packet::Packet (const Packet &p)
{
  this->bufLen = p.bufLen;
  this->pktLen = p.pktLen;
  this->capLen = p.capLen;
  this->remain = p.capLen;
  this->cursol = 0;
  this->tv.tv_sec = p.tv.tv_sec;
  this->tv.tv_usec = p.tv.tv_usec;

  this->data = new byte_t [this->bufLen];
  memcpy (this->data, p.data, this->bufLen);
}

Packet::~Packet ()
{
  if (data)
    delete [] data;
}

Packet &Packet::operator=(const Packet &p)
{
  if (this->bufLen < p.capLen)
    {
      if (this->data)
	delete [] this->data;
      
      this->bufLen = p.capLen;
      this->data = new byte_t [this->bufLen];
    }

  memcpy (this->data, p.data, this->bufLen);

  this->pktLen = p.pktLen;
  this->capLen = p.capLen;
  this->remain = p.capLen;
  this->cursol = 0;
  this->tv.tv_sec = p.tv.tv_sec;
  this->tv.tv_usec = p.tv.tv_usec;

  return (*this);
}


void 
Packet::setData (byte_t * p, int len, int capLen, struct timeval * tv)
{
  if (capLen > this->bufLen)
    {
      if (this->data)
	delete [] this->data;

      this->data = new byte_t [capLen];
      this->bufLen = capLen;
    }

  memcpy (this->data, p, capLen);
  memcpy (&this->tv, tv, sizeof (struct timeval));
  this->pktLen = len;
  this->capLen = capLen;
  this->cursol = 0;
  return ;
}

void * Packet::getCur ()
{
  assert (0 <= this->cursol && this->cursol <= this->capLen);

  if (this->cursol == this->capLen)
    return NULL;
  else
    return (void*) &(this->data[this->cursol]);
}

bool Packet::moveCur (int n)
{
  assert (n >= 0);
  assert (this->remain <= this->capLen);
  if (this->cursol + n > this->remain)
    {
      return false;
    }

  this->cursol += n;
  return true;
}

void Packet::setRemain (int n)
{
  if (this->cursol + n <= this->remain)
    this->remain = this->cursol + n;
}
